package cz.cvut.fit.mi_paa.bucket;

import cz.cvut.fit.mi_paa.abs.Context;
import cz.cvut.fit.mi_paa.abs.Instance;
import cz.cvut.fit.mi_paa.utils.StopWatch;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: milos
 * Date: 1.10.12
 * Time: 11:08
 * To change this template use File | Settings | File Templates.
 */
public class BucketContext extends Context {
    private BucketInstance instance;
    private Queue<BucketInstance> queue;

    public BucketContext(FileWriter resultWriter, BufferedReader inputReader, StopWatch sw) {
        super(resultWriter,inputReader, sw);
    }

    public boolean nextInstance() throws IOException {
        String instanceString = inputReader.readLine();
        if(instanceString!=null) {
            String[] numbers = instanceString.split("\\s+");

            int id = Integer.valueOf(numbers[0]);
            int bucketCount = Integer.valueOf(numbers[1]);
            Bucket[] buckets = new Bucket[bucketCount];
            int[] finalConfiguration = new int[bucketCount];
            getConfiguration(numbers,buckets,finalConfiguration, bucketCount);

            this.instance = new BucketInstance(id,bucketCount,buckets,finalConfiguration,new ArrayList<Operation>());
            return true;
        } else {
            return false;
        }

    }


    public void close() throws IOException {
        resultWriter.close();
        inputReader.close();
    }

    private void getConfiguration(String[] numbers, Bucket[] buckets, int[] configuration, int arraySize) {
        for(int i=0;i<arraySize;i++) {
            buckets[i] = new Bucket(Integer.valueOf(numbers[i+arraySize+2]),Integer.valueOf(numbers[i+2]));
            configuration[i] = Integer.valueOf(numbers[i+2*arraySize+2]);
        }
    }

    public Instance getInstance() {
        return instance;
    }

    public Queue<BucketInstance> getQueue() {
        return queue;
    }

    public void setQueue(Queue<BucketInstance> queue) {
        this.queue = queue;
    }
}
